package user

import (
	"api-go/model"
	"api-go/serializer"
)

// 用户注册所需信息
type UserUpdateService struct {
	Password string `form:"password" binding:"max=18"`
	Email    string `form:"email" binding:"email"`
	Avatar   string `form:"avatar"`
	Nickname string `form:"nickname"`
}

// 验证表单
func (service *UserUpdateService) Valid(user *model.User) *serializer.Response {

	// 新更换的邮箱已存在
	if user.Email != service.Email {
		ress := model.DB.Where("email = ?", service.Email).First(&model.User{})
		if ress.RowsAffected > 0 {
			return serializer.ErrorResponse(serializer.CodeEmailExistError)
		}
	}
	return nil
}

// 用户信息更新
func (service *UserUpdateService) UpdateUserInfo(user *model.User) *serializer.Response {

	// 表单验证
	if err := service.Valid(user); err != nil {
		return err
	}

	//更新邮箱
	if val := service.Email; val != "" {
		service.Email = val
	} else {
		service.Email = user.Email
	}

	//更新头像
	if val := service.Avatar; val != "" {
		service.Avatar = val
	} else {
		service.Avatar = user.Avatar
	}

	//更新昵称
	if val := service.Nickname; val != "" {
		service.Nickname = val
	} else {
		service.Nickname = user.Nickname
	}

	newUser := model.User{
		Nickname: service.Nickname,
		Email:    service.Email,
		Avatar:   service.Avatar,
	}

	//未更改密码，则保持原来的
	if val := service.Password; val != "" {
		service.Password = val
		// 加密密码
		if err := newUser.SetPassword(service.Password); err != nil {
			return serializer.ErrorResponse(serializer.CodeUnknownError)
		}
	}

	// 更新用户
	if err := model.DB.Model(&user).Updates(&newUser).Error; err != nil {
		return serializer.ErrorResponse(serializer.CodeUnknownError)
	}
	// 响应信息
	data := serializer.BuildUserResponse(&newUser)
	return serializer.OkResponse(data)
}
